﻿using Autofac;
using Autofac.Extensions.DependencyInjection;
using DeZhen.DataCollection.WebApi.Configurations;
using SqlSugar;
using Yitter.IdGenerator;
using Hangfire;
using Hangfire.MySql;
using Hangfire.SqlServer;
using Serilog;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

//替换内置依赖注入容器为Autofac
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<Autofac.ContainerBuilder>(container =>
{
    // 注册Serilog
    container.RegisterInstance(Log.Logger).As<Serilog.ILogger>().SingleInstance();

    //注册Autofac模块
    container.RegisterModule(new AutofacModuleRegister());

    //注册 SqlSugar
    //container.Register<ISqlSugarClient>(context =>
    //{
    //    SqlSugarClient db = new SqlSugarClient(new ConnectionConfig()
    //    {
    //        DbType = (DbType)Convert.ToInt32(builder.Configuration.GetSection("ConnectionStrings")["dbType"]),//DbType.MySql,
    //        //DbType = DbType.SqlServer,
    //        IsAutoCloseConnection = true,
    //        ConnectionString = builder.Configuration.GetSection("ConnectionStrings")["connStr"],
    //    });

    //    return db;
    //});
    container.Register<ISqlSugarClient>(context =>
    {
        var config = new ConnectionConfig()
        {
            DbType = (DbType)Convert.ToInt32(builder.Configuration["ConnectionStrings:dbType"]),
            ConnectionString = builder.Configuration["ConnectionStrings:connStr"],
            IsAutoCloseConnection = true //自动关闭连接
        };

        var db = new SqlSugarClient(config);

        // 启用日志记录（可用于调试 SQL）
        //db.Aop.OnLogExecuting = (sql, parameters) =>
        //{
        //    Log.Logger.Information(sql);
        //};

        return db;
    })
    .InstancePerLifetimeScope();
});

//AutoMapper映射
builder.Services.AddAutoMapper(typeof(AutoMapperConfigs));

// 配置雪花Id算法
YitIdHelper.SetIdGenerator(new IdGeneratorOptions { WorkerId = 1 });

// 配置swagger
builder.Services.AddSwaggerGen(options =>
{
    // 添加 WebApi 的 XML 注释文件
    var apiXmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
    var apiXmlPath = Path.Combine(AppContext.BaseDirectory, apiXmlFile);
    if (File.Exists(apiXmlPath))
    {
        options.IncludeXmlComments(apiXmlPath, true);
    }


    // 添加 Model 层的 XML 注释
    var modelXmlFile = "DeZhen.DataCollection.Model.xml";
    var modelXmlPath = Path.Combine(AppContext.BaseDirectory, modelXmlFile);
    if (File.Exists(modelXmlPath))
    {
        options.IncludeXmlComments(modelXmlPath, true);
    }
});

// 配置全局过滤器
builder.Services.AddControllers(options =>
{
    options.Filters.Add<ApiResponseWrapperAttribute>();
});


// 配置Hangfire
builder.Services.AddHangfire(configuration =>
{
    configuration.UseStorage(
        new MySqlStorage(builder.Configuration.GetSection("ConnectionStrings")["connStr"],
            new MySqlStorageOptions
            {
                // 设置Hangfire的表前缀
                TablesPrefix = "hangfire_",
            }
        )
    );
});
//builder.Services.AddHangfire(configuration =>
//{
//    configuration.UseStorage(
//        new SqlServerStorage(builder.Configuration.GetSection("ConnectionStrings")["connStr"],
//            new SqlServerStorageOptions
//            {
//                // 设置Hangfire的表前缀
//                SchemaName = "hangfire_",
//            }
//        )
//    );
//});

builder.Services.AddHangfireServer();

// 添加CORS服务
builder.Services.AddCors(options =>
{
    options.AddPolicy("AllowAll", policy =>
    {
        policy.AllowAnyOrigin()    // 允许任何来源
              .AllowAnyMethod()   // 允许任何HTTP方法（GET, POST等）
              .AllowAnyHeader();  // 允许任何请求头
    });
});


//配置 Serilog
builder.Host.UseSerilog((context, services, configuration) => configuration
    .ReadFrom.Configuration(context.Configuration) // 从 appsettings.json 读取配置
    .WriteTo.Console()                            // 输出到控制台
    .WriteTo.File("logs/log-.txt", rollingInterval: RollingInterval.Day) // 按天滚动日志文件
    .Enrich.FromLogContext()                     // 添加上下文信息（如请求ID）
);

var app = builder.Build();

//获取ILogger实例
//var logger = app.Services.GetRequiredService<ILogger<Program>>();
//logger.LogInformation("Application starting...");

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{

}

app.UseSwagger();
app.UseSwaggerUI();

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

//使用跨域策略
app.UseCors("AllowAll");


app.Run();
